package zhou.jan22;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class UserDao {    //只做数据库操作
	
	BaseDao basedao=new BaseDao();
	Connection con=null;
	PreparedStatement ps=null;
	ResultSet rs=null;
	
	//登录：
	public User getUserByName(String name) throws SQLException{   //
		
		con=basedao.getCon();
		String sql="select * from user where username=?";
		ps=con.prepareStatement(sql);
		ps.setString(1, name);
		rs=ps.executeQuery();
		String pwd="";
		
		while (rs.next()){    
			pwd=rs.getString("userpwd");   
			//id=r					
		}
		closeData();
		User u=new User(name,pwd);
		return u;
	}
	
	//用户注册，添加用户：
	public boolean addUser(User u) throws SQLException{
		boolean flag=false;
		con=basedao.getCon();
		String sql="insert into user (username,userpwd) values(?,?)";
        ps=con.prepareStatement(sql);
		ps.setString(1, u.getName());
		ps.setString(2, u.getPwd());		
		if(ps.executeUpdate()>0){
				flag=true;
			}		
		closeData();
		
		return flag;
	}
	
	//判断商店名称是否重名：
    public boolean getShopByName(User u) throws SQLException{   //
    	boolean result=false;
		con=basedao.getCon();
		String sql="select * from shop where shopName=?";
		ps=con.prepareStatement(sql);
		ps.setString(1, u.getShop().getShopName());
		rs=ps.executeQuery();		
		if(rs.next()){
			if(rs.getString("shopName")!=null);
			return result;
		}
		else{
			result=true;
		}
		closeData();
		
		return result;
	}
	
     //申请添加商店：
	 public boolean addShop(User u) throws SQLException{
		boolean result=false;	    
	    con=basedao.getCon();	    	
	    String sql="insert into shop (shopName,username) value (?,?)";	    
	       			  	
		PreparedStatement ps=con.prepareStatement(sql);   	
		ps.setString(1, u.getShop().getShopName());
		ps.setString(2, u.getName());	  //与登录时用户名一样
		if(ps.executeUpdate()>0){
			result=true;
			System.out.println("申请开店成功");
		}		
	     closeData();			    				    
	     return result;
	}
	
	//添加商品:
	 public boolean addCommodity(Shop s) throws SQLException{
		 boolean result=false;	    
		    con=basedao.getCon();	    	
		    String sql="insert into commodity (name,price,number) value (?,?,?) where commodity.commodityId=shop.commodityId";	    
		       			  	
			PreparedStatement ps=con.prepareStatement(sql);   	
			ps.setString(1, s.getCommodity().getName());
			ps.setDouble(2, s.getCommodity().getPrice());
			ps.setInt(3, s.getCommodity().getNumber());
			if(ps.executeUpdate()>0){
				result=true;
				System.out.println("添加商品成功");
			}		
		    closeData();				    						    
		    return result;
	 }
	
	
	
	
	
	
	
	
	
	
	public void closeData() throws SQLException{
		if(rs!=null){
			rs.close();
		}
		if(ps!=null){
			ps.close();
		}
		if(con!=null){
			con.close();
		}
	}

}
